package com.cuz.series.linklist;

public class 链表12旋转链表 {

    public static void main(String[] args) {
        ListNode head = ListNode.of1(1, 2, 3, 4, 5);

        rotateRight1(head,6).print();
    }
    public static ListNode rotateRight1(ListNode head, int k) {

        if (head == null || head.next == null) {
            return head;
        }
        //长度和头
        Object[] lenAndTail = lenAndTail(head);

        int len = (int) lenAndTail[0];
        //比如长度是5 k是12 其实等价于k=2
        int mode = k % len;
        //整除 说明恢复到原样了
        if (mode == 0) {
            return head;
        }
        //尾巴
        ListNode tail = (ListNode) lenAndTail[1];
        //走到多少不 比如 1->2->3->4->5 k=2 那么走2步
        int step = len - mode - 1;
        ListNode point = head;
        for (int i = 0; i < step; i++) {
            point = point.next;
        }
        //走两部 point到3 这个时候4是就是新的头
        ListNode newHead = point.next;
        //断开3 和 4
        point.next=null;
        //把尾部连接到头 实现旋转
        tail.next=head;
        return newHead;
    }

    private static Object[] lenAndTail(ListNode head) {
        int len = 0;
        ListNode tail = head;
        while (head != null) {
            if (head.next == null) {
                tail = head;
            }
            head = head.next;
            len++;
        }
        return new Object[]{len, tail};
    }

}
